public class SolutionInterview17_6 {
    public int numberOf2sInRange(int n) {
        String num=String.valueOf(n);
        int ans=0;
        for (int i=0;i<num.length();i++){
            if (i==0){
                int t=1;
                for (int j=0;j<num.length()-1;j++){
                    t*=10;
                }
                if (num.charAt(i)>'2'){
                    ans+=t;
                }else if (num.charAt(i)=='2'){
                    ans+=n%t+1;
                }
            }else if (i==num.length()-1){
                ans+=n/10;
                if (n>=n/10*10+2){
                    ans++;
                }
            }else {
                int t=1;
                for (int j=i;j<num.length()-1;j++){
                    t*=10;
                }
                int p=t*10;
                ans+=n/p*t;
                if (num.charAt(i)>'2'){
                    ans+=t;
                }else if (num.charAt(i)=='2'){
                    ans+=n%t+1;
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new SolutionInterview17_6().numberOf2sInRange(251));
    }
}
